//
//  RecommendTableViewController.m
//  YouMin_iOS
//
//  Created by lanou3g on 15/12/10.
//  Copyright © 2015年 wey. All rights reserved.
//

#import "RecommendTableViewController.h"
#import "SDCycleScrollView.h"
#import "EntityModel.h"
#import "SecondCollectionViewCell.h"
#import "ThirdTableViewCell.h"
#import "MoreStoryCollectionVC.h"
#import "SearcherViewController.h"


@interface RecommendTableViewController ()<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UICollectionViewDelegate,SDCycleScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *flowLayout;
// 设置轮播图数据
@property (nonatomic, strong) NSMutableArray *sectionArray1;
///  每日精选故事 数组 (4 个)
@property (nonatomic, strong) NSMutableArray *sectionArray2;
///  精彩游记和专题 可变数组
@property (nonatomic, strong) NSMutableArray *sectionArray3;
///  当前时间戳
@property (nonatomic, strong) NSString *currentTime;
///  搜索button数组[0]国外[1]国内
@property (nonatomic, strong) NSMutableArray *searchArrays;
///  sectionTitle1
@property (weak, nonatomic) IBOutlet UILabel *sectionLabel1;
///  sectionTitle2
@property (weak, nonatomic) IBOutlet UILabel *sectionLabel2;
///  轮播
@property (weak, nonatomic) IBOutlet SDCycleScrollView *cycleView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *cycleHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *collectionHeight;

@end

@implementation RecommendTableViewController

- (NSMutableArray *)sectionArray1 {
    if (!_sectionArray1) {
        _sectionArray1 = [NSMutableArray array];
    }
    return _sectionArray1;
}

- (NSMutableArray *)sectionArray2 {
    if (!_sectionArray2) {
        _sectionArray2 = [NSMutableArray arrayWithCapacity:4];
    }
    return _sectionArray2;
}

- (NSMutableArray *)sectionArray3 {
    if (!_sectionArray3) {
        _sectionArray3 = [NSMutableArray arrayWithCapacity:12];
    }
    return _sectionArray3;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadData];
    [self setLayout];
    ///  这里顺序有问题

    // 上 刷新 ,下 加载
    kWeakSelf(weakSelf);
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [weakSelf loadData]; // 重新请求一下
        [weakSelf.tableView.mj_header endRefreshing];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self pushMoreData];
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
    
    
}

- (void)setLayout {
    CGFloat kHeight = [UIScreen mainScreen].bounds.size.height;
    self.flowLayout.minimumInteritemSpacing = 5.0;
    self.flowLayout.minimumLineSpacing = 5.0;
    self.flowLayout.sectionInset = UIEdgeInsetsMake(0.1, 5, 0.1, 5);
    self.collectionView.backgroundColor = [UIColor whiteColor];

///  headerView  大小
    CGFloat headerHeight = kHeight*5/6-20;
    self.tableView.tableHeaderView.frame = CGRectMake(0, 0, kScreenWith, headerHeight);
    self.cycleHeight.constant = headerHeight*2/5 ;
    self.collectionHeight.constant = headerHeight*3/5 - 58.0;
        self.flowLayout.itemSize = CGSizeMake((kScreenWith -15)/2,(headerHeight*3/5 - 64.0)/2 );
    self.tableView.rowHeight = kHeight*2/7;
}
///  请求数据
- (void)loadData {
    
    kWeakSelf(weakSelf);
    // 数据库 判断是否 有缓存 钥匙串
    [[NetWorkHelper shareInstance] GET:kRecommendUrl parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary *dic = responseObject;
        dic = dic[@"data"];
        [weakSelf setUpDataWith:dic];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@,%s",error,__func__);
    }];
    
}

// 下拉刷新
- (void)pushMoreData {
    kWeakSelf(weakSelf);
    
    NSMutableArray *subArr = [NSMutableArray arrayWithCapacity:10];
    NSString *urlStr = [NSString stringWithFormat:@"http://api.breadtrip.com/v2/index/?next_start=%@",self.currentTime];
    [[NetWorkHelper shareInstance] GET:urlStr parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary *dic = responseObject;
        weakSelf.currentTime =  dic[@"data"][@"next_start"];
        NSArray *elements = dic[@"data"][@"elements"];
        [elements enumerateObjectsUsingBlock:^(NSDictionary *  obj, NSUInteger idx, BOOL * _Nonnull stop) {
            EntityModel *model = [EntityModel entityModelWithDic:obj[@"data"][0]];
            model.type = [elements[idx][@"type"] intValue] ;
            model.nickImgUrl = elements[idx][@"data"][0][@"user"][@"avatar_s"];
            model.nickName = elements[idx][@"data"][0][@"user"][@"name"];
            [subArr addObject:model];
            
            
            [weakSelf.tableView reloadData];
        }];
        [weakSelf.sectionArray3 addObjectsFromArray:subArr];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
    
    
    
}

- (void) setUpDataWith:(NSDictionary *)dic{
    
    [self.sectionArray1 removeAllObjects];
    [self.sectionArray2 removeAllObjects];
    [self.sectionArray3 removeAllObjects];
    self.currentTime = [dic[@"next_start"] stringValue];
    ///  搜索数组 国内 国外
    self.searchArrays = dic[@"search_data"];
    ///  取轮播图 title urls
    NSArray *elements = dic[@"elements"];
    for (NSDictionary *dic in elements.firstObject[@"data"][0]) {
        NSArray *subs = @[dic[@"image_url"],dic[@"html_url"]];
        [self.sectionArray1 addObject:subs];
    }
    ///  title
    self.sectionLabel1.text = elements[1][@"data"][0][@"title"];
    self.sectionLabel2.text = elements[6][@"data"][0][@"title"];
    
    ///  4 个小图
    for (int i=2; i<6; i++) {
        NSDictionary *dic = elements[i][@"data"][0];
        EntityModel *model = [EntityModel entityModelWithDic:dic];
        model.nickImgUrl = dic[@"user"][@"avatar_s"];
        model.nickName = dic[@"user"][@"name"];
        
        [self.sectionArray2 addObject:model];
    }
    ///  其余大图
    for (int i = 7; i<elements.count; i++) {
        int typeNum = [elements[i][@"type"] intValue];
        if ((typeNum == 4) || (typeNum == 12)) {
            NSDictionary *dic = elements[i][@"data"][0];
            EntityModel *model = [EntityModel entityModelWithDic:dic];
            model.nickImgUrl = elements[i][@"data"][0][@"user"][@"avatar_s"];
            model.nickName = elements[i][@"data"][0][@"user"][@"name"];
            model.type = typeNum;
            [self.sectionArray3 addObject:model];
            
        }
    }
    [self loadCycleView];
    [self.tableView reloadData];
    [self.collectionView reloadData];
    
}


#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.sectionArray3.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ThirdTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell2" forIndexPath:indexPath];
    cell.model = self.sectionArray3[indexPath.item];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    EntityModel *model = self.sectionArray3[indexPath.row];
    NSString *url = [NSString stringWithFormat:@"http://api.breadtrip.com/trips/%ld/waypoints/",model.trip_id];
    NSLog(@"%@",url);
}

#pragma mark --- Collection View Data Source
- (void)loadCollectionView {
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.sectionArray2.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SecondCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"secondCell" forIndexPath:indexPath];
    cell.model = self.sectionArray2[indexPath.item];

    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    EntityModel *model = self.sectionArray2[indexPath.item];
    NSString *str = [NSString stringWithFormat:@"http://api.breadtrip.com/v2/new_trip/spot/?spot_id=%ld",model.spot_id];
    NSLog(@"%@",str);
    
    
}
#pragma mark --- CycleView Data
- (void)loadCycleView {
    
    NSMutableArray *imgUrls = [NSMutableArray arrayWithCapacity:self.sectionArray1.count];
    NSMutableArray *htmlUrls = [NSMutableArray arrayWithCapacity:self.sectionArray1.count];
    
    [self.sectionArray1 enumerateObjectsUsingBlock:^(NSArray * obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [imgUrls addObject:obj.firstObject];
        [htmlUrls addObject:obj.lastObject];
    }];
    self.cycleView.imageURLStringsGroup = imgUrls;
    self.cycleView.delegate = self;
    
}
/** 轮播图点击事件 */

/*
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    
    UIViewController *webVC = [[UIViewController alloc]init];
    NSString *str = [self.sectionArray1.lastObject lastObject];
    NSError *error = nil;
    NSString *pageStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:str] encoding:NSUTF8StringEncoding error:&error];
    NSLog(@"%@",pageStr);
    
    
    
//    AFHTTPSessionManager *mgr = [NetWorkHelper shareInstance].copy;
//    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
//    [mgr GET:str parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
//        NSLog(@"%@,%@",responseObject,[responseObject class]);
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"%@,%s",error,__func__);
//    }];
    
    UIWebView *webView =[[UIWebView alloc]init];
    [webView loadHTMLString:pageStr baseURL:nil];
    
//    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:str]];
//    UIWebView *webView = [[UIWebView alloc]initWithFrame:self.tableView.frame];
    webView.scalesPageToFit = YES;
    webView.scrollView.showsVerticalScrollIndicator = NO;
    webView.scrollView.bounces = NO;
    webVC.view.backgroundColor = [UIColor redColor];
//    [webView loadRequest:request];
//    webView.scrollView.bounces = NO;
    [webVC.view addSubview:webView];
    [self presentViewController:webVC animated:YES completion:nil];
    
}
 
 */

// 跳入搜索页面
- (IBAction)SearchAction:(id)sender {
    
    [self performSegueWithIdentifier:@"search" sender:self];
}

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([segue.identifier isEqualToString:@"search"]) {
        SearcherViewController *searchVC = segue.destinationViewController;
        searchVC.items = [self.searchArrays copy];
    }
}

- (IBAction)leftMenuAction:(id)sender {
    
    [self.sideMenuViewController presentLeftMenuViewController];
}
//
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
